﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

using MiniTwitter.Extensions;
using MiniTwitter.Input;
using MiniTwitter.Themes;
using MiniTwitter.Properties;

namespace MiniTwitter
{
    /// <summary>
    /// App.xaml の相互作用ロジック
    /// </summary>
    public partial class App : Application
    {
        private void App_Startup(object sender, StartupEventArgs e)
        {
            if (!mutex.WaitOne(0, false))
            {
                MessageBox.Show("既に起動しています。", App.NAME);
                Shutdown();
                return;
            }
            KeyMapping.LoadFrom(Environment.CurrentDirectory);
            ThemeManager.LoadFrom(Environment.CurrentDirectory);
            // 設定を読み込む
            Settings.Load(directory);
            if (Settings.Default.Theme.IsNullOrEmpty() || !ThemeManager.Themes.ContainsValue(Settings.Default.Theme))
            {
                // デフォルトのテーマ
                Settings.Default.Theme = ThemeManager.GetTheme(0);
            }
            this.ApplyTheme(Settings.Default.Theme);
        }

        private void App_Exit(object sender, ExitEventArgs e)
        {
            if (!_isSaved)
            {
                Settings.Save();
                _isSaved = true;
            }
        }

        private void App_SessionEnding(object sender, SessionEndingCancelEventArgs e)
        {
            if (!_isSaved)
            {
                Settings.Save();
                _isSaved = true;
            }
        }

        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
#if !DEBUG
            if (e.Exception == null)
            {
                return;
            }
            string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), @"MiniTwitter_Exception.log");
            using (StreamWriter writer = new StreamWriter(path))
            {
                writer.WriteLine("{0} ver {1}", NAME, VERSION);
                writer.WriteLine();
                writer.WriteLine("Message:");
                writer.WriteLine(e.Exception.Message);
                writer.WriteLine();
                writer.WriteLine("StackTrace:");
                writer.WriteLine(e.Exception.StackTrace);
            }
#endif
        }

        private bool _isSaved = false;

        private readonly Mutex mutex = new Mutex(false, NAME);

        private readonly string directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), NAME);

        public const string VERSION = "1.02";
        public const string NAME = "MiniTwitter";
    }
}
